#include <stdio.h>
#include <malloc.h>
#include "registers.h"
#include "file.h"
#include "command.h"
#include "memory.h"

int main() {
    registers r;
    init_registers(&r);
    Memory memory = create_memory(7 * 1024);
    unsigned char *bin = file_get_binary("main.hoe");
    CommandRet cmd = parse_command(bin, filesize("main.hoe"));
    free(bin);
    for (unsigned long long int i = 0; i < cmd.size; ) {
        if (cmd.cmd[i].cmd == JMP ||
            (cmd.cmd[i].cmd == JZ && r.ZF) ||
            (cmd.cmd[i].cmd == JNZ && !r.ZF)) {
            i += cmd.cmd[i].offset;
        } else if ((cmd.cmd[i].cmd == JZ && !r.ZF) ||
                   (cmd.cmd[i].cmd == JNZ && r.ZF)) {
            ++i;
        } else {
            int ret = execute_command(cmd.cmd[i], &r, memory);
            printf("ret:%d r2:%d r3:%d\n", ret, r.R[2], r.R[3]);
            if (ret == -1) {
                ++i;
                continue;
//                show_registers(r);
            } else if (ret == -2) {
                printf("execute failed\n");
                break;
            } else if (ret == 0) {
                printf("div 0\n");
                break;
            } else if (ret == 5) {
                unsigned char len = memory.memory[r.DS];
                ++r.DS;
                for (int j = r.DS; j < len; ++j) {
                    printf("%c", memory.memory[j]);
                }
                r.DS += len;
            }
            ++i;
        }
    }
    free(cmd.cmd);
    release_memory(memory);

    return 0;
}
